import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:yi_shop/model/product.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class BargainController extends GetxController {
  List<String> tagList = ['挑选商品', '免单砍价', '邀请好友', '商品免单'];

  List<String> attrs = ['红色', '蓝色', '橙色', '绿色'];

  RxInt attrIndex = 0.obs;

  RxList<BargainProductModel> pageList = RxList([]);

  int total = 30;

  RxBool isLoading = false.obs;

  RxBool hasNext = true.obs;

  void startLoading() {
    isLoading.value = true;
    hasNext.value = true;
    futureLoadData().then((List<BargainProductModel> data) {
      addLoadData(data);
    });
  }

  @override
  void onInit() {
    initData();
    super.onInit();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(BargainProductModel(
          imgUrl:
              'https://img.alicdn.com/img/i4/12018689/O1CN01C4hp2G2E3c5g52FjL_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
          name: '韩都衣舍2019夏装新款',
          sendCount: r.nextInt(500) + 152));
    }
  }

  List<BargainProductModel> loadDataMore() {
    Random r = Random.secure();
    List<BargainProductModel> pageList = [];
    for (var i = 0; i < 10; i++) {
      pageList.add(BargainProductModel(
          imgUrl:
              'https://img.alicdn.com/img/i4/12018689/O1CN01C4hp2G2E3c5g52FjL_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
          name: '韩都衣舍2019夏装新款',
          sendCount: r.nextInt(500) + 152));
    }
    return pageList;
  }

  Future<List<BargainProductModel>> futureLoadData() async {
    return Future.delayed(const Duration(milliseconds: 3000), () {
      return loadDataMore();
    });
  }

  void addLoadData(List<BargainProductModel> data) {
    isLoading.value = false;
    if (pageList.length < total) {
      hasNext.value = true;
      pageList.addAll(data);
      return;
    }
    hasNext.value = false;
  }
}

class BargainPage extends GetView<BargainController> {
  const BargainPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        leading: ToolsUtils.builderLeading(),
        title: const Text('砍价专区'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 20.h),
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 25.w,
                    backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF26f),
                    child: SvgUtils.assetName('u7732', width: 20.w, height: 20.h),
                  ),
                  Expanded(
                      child: Center(
                    child: Container(
                      height: 1,
                      width: 35.w,
                      decoration: BoxDecoration(
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF26f),
                      ),
                    ),
                  )),
                  CircleAvatar(
                    radius: 25.w,
                    backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF26f),
                    child: SvgUtils.assetName('u7737', width: 20.w, height: 20.h),
                  ),
                  Expanded(
                      child: Center(
                    child: Container(
                      height: 1,
                      width: 35.w,
                      decoration: BoxDecoration(
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF26f),
                      ),
                    ),
                  )),
                  CircleAvatar(
                    radius: 25.w,
                    backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF26f),
                    child: SvgUtils.assetName('u7743', width: 20.w, height: 20.h),
                  ),
                  Expanded(
                      child: Center(
                    child: Container(
                      height: 1,
                      width: 35.w,
                      decoration: BoxDecoration(
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF26f),
                      ),
                    ),
                  )),
                  CircleAvatar(
                    radius: 25.w,
                    backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF26f),
                    child: SvgUtils.assetName('u7751', width: 20.w, height: 20.h),
                  ),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 10.h),
              child: Row(
                children: controller.tagList
                    .map((e) => Expanded(
                            child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.symmetric(horizontal: 15.w),
                          child: Text(
                            e,
                            style: StylesUtils.customTextStyle(
                                fontSize: StylesUtils.fontSize13, color: ColorsUtils.color3333),
                          ),
                        )))
                    .toList(),
              ),
            ),
            Obx(() => Container(
                  margin: EdgeInsets.only(top: 20.h),
                  padding: EdgeInsets.symmetric(horizontal: 15.w),
                  child: StaggeredGrid.count(
                    crossAxisCount: 2,
                    crossAxisSpacing: 10.w,
                    mainAxisSpacing: 15.h,
                    children: controller.pageList
                        .map((e) => Column(
                              children: [
                                Stack(
                                  children: [
                                    ClipRRect(
                                      borderRadius: BorderRadius.circular(5.r),
                                      child: CachedNetworkImage(
                                        imageUrl: e.imgUrl,
                                        width: 164.w,
                                        height: 218.h,
                                        fit: BoxFit.fill,
                                        // color: ColorsUtils.parseColorFromHexString(
                                        //     ColorsUtils.colorFbb8),
                                      ),
                                    ),
                                    Positioned(
                                        left: 0,
                                        right: 0,
                                        bottom: 0,
                                        child: Container(
                                          height: 39.h,
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.only(
                                                  bottomLeft: Radius.circular(5.r),
                                                  bottomRight: Radius.circular(5.r)),
                                              color: ColorsUtils.rgba(253, 224, 229, 1)),
                                          child: Text.rich(TextSpan(
                                              style: StylesUtils.customTextStyle(
                                                fontSize: StylesUtils.fontSize13,
                                                color: ColorsUtils.color5555,
                                              ),
                                              children: [
                                                const TextSpan(text: '已送出'),
                                                TextSpan(
                                                    text: '${e.sendCount}',
                                                    style: StylesUtils.customTextStyle(
                                                      fontSize: StylesUtils.fontSize13,
                                                      color: ColorsUtils.colorF048,
                                                    )),
                                                const TextSpan(text: '件')
                                              ])),
                                        ))
                                  ],
                                ),
                                Container(
                                  margin: EdgeInsets.symmetric(vertical: 8.h),
                                  alignment: Alignment.center,
                                  child: Text(
                                    e.name,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: StylesUtils.customTextStyle(
                                        fontSize: StylesUtils.fontSize13,
                                        color: ColorsUtils.color3333),
                                  ),
                                ),
                                Container(
                                  height: 30.h,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(15.r),
                                      color: ColorsUtils.parseColorFromHexString(
                                          ColorsUtils.colorF048)),
                                  child: TextButton(
                                    onPressed: openAlert,
                                    child: Text(
                                      '点击免费拿',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.colorF7f7,
                                          fontSize: StylesUtils.fontSize13),
                                    ),
                                  ),
                                )
                              ],
                            ))
                        .toList(),
                  ),
                )),
            Obx(() => loadData())
          ],
        ),
      ),
    );
  }

  Widget loadData() {
    if (controller.isLoading.isTrue && controller.hasNext.isTrue) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 10.h),
        child: FractionallySizedBox(
            widthFactor: 0.8,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                    child: Container(
                  height: 1,
                  color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
                )),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 10.w),
                  alignment: Alignment.center,
                  child: const CircularProgressIndicator(
                    strokeWidth: 3,
                  ),
                ),
                Expanded(
                    child: Container(
                  height: 1,
                  color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
                ))
              ],
            )),
      );
    }
    if (controller.hasNext.isTrue) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 10.h),
        child: FractionallySizedBox(
            widthFactor: 0.9,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                    child: Center(
                  child: Container(
                    height: 1,
                    color: ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                  ),
                )),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 10.w),
                  alignment: Alignment.center,
                  child: Wrap(
                    spacing: 5.w,
                    alignment: WrapAlignment.spaceBetween,
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      TextButton(
                          onPressed: controller.startLoading,
                          child: Text(
                            '查看更多',
                            style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize13),
                          )),
                      SvgUtils.assetName('u7806', width: 12.w, height: 12.h)
                    ],
                  ),
                ),
                Expanded(
                    child: Center(
                  child: Container(
                    height: 1,
                    color: ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                  ),
                ))
              ],
            )),
      );
    }
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 10.h),
      child: FractionallySizedBox(
          widthFactor: 0.9,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                  child: Center(
                child: Container(
                  height: 1,
                  color: ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                ),
              )),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 10.w),
                alignment: Alignment.center,
                child: Text(
                  '我是有底线的',
                  style: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333, fontSize: StylesUtils.fontSize13),
                ),
              ),
              Expanded(
                  child: Center(
                child: Container(
                  height: 1,
                  color: ColorsUtils.parseColorFromHexString(ColorsUtils.color9999),
                ),
              ))
            ],
          )),
    );
  }

  void openAlert() {
    Get.bottomSheet(Container(
      height: 300.h,
      decoration: const BoxDecoration(color: Colors.white),
      child: Column(
        children: [
          Container(
            height: 60.h,
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorE4e4)))),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Transform.translate(
                  offset: Offset(0, -15.h),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(5.r),
                    child: CachedNetworkImage(
                      imageUrl:
                          'https://img.alicdn.com/img/i4/3255687462/O1CN01adQt6K24zeL8Zciua_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
                      width: 70.h,
                      height: 70.h,
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
                Expanded(
                    child: Container(
                  padding: EdgeInsets.only(left: 10.w),
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.only(top: 10.h),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '￥99',
                          style: StylesUtils.customTextStyle(
                              fontWeight: FontWeight.w500, color: ColorsUtils.colorF95e),
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.only(top: 5.h),
                        child: Text(
                          '商品编号:4224095',
                          style: StylesUtils.customTextStyle(
                              color: ColorsUtils.color9999, fontSize: StylesUtils.fontSize12),
                        ),
                      )
                    ],
                  ),
                )),
                Align(
                  alignment: Alignment.topRight,
                  child: IconButton(
                    icon: Icon(
                      Icons.close_outlined,
                      size: 20,
                      color: ColorsUtils.parseColorFromHexString(ColorsUtils.color6666),
                    ),
                    onPressed: () {
                      Get.back();
                    },
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.only(top: 15.h, bottom: 10.h),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '颜色',
                      style: StylesUtils.customTextStyle(
                        color: ColorsUtils.color9999,
                      ),
                    ),
                  ),
                  Obx(() => StaggeredGrid.count(
                        crossAxisCount: 2,
                        crossAxisSpacing: 10.w,
                        mainAxisSpacing: 10.h,
                        children: controller.attrs
                            .asMap()
                            .map((key, value) => MapEntry(
                                key,
                                InkWell(
                                  onTap: () {
                                    controller.attrIndex.value = key;
                                  },
                                  child: Container(
                                    constraints:
                                        BoxConstraints.tightFor(width: 138.w, height: 25.h),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(5.r),
                                        border: Border.all(
                                            color: key == controller.attrIndex.value
                                                ? ColorsUtils.parseColorFromHexString(
                                                    ColorsUtils.colorF048)
                                                : ColorsUtils.parseColorFromHexString(
                                                    ColorsUtils.colorCccc))),
                                    child: Text(
                                      value,
                                      style: StylesUtils.customTextStyle(
                                          fontSize: StylesUtils.fontSize12,
                                          color: key == controller.attrIndex.value
                                              ? ColorsUtils.colorF048
                                              : ColorsUtils.color9999),
                                    ),
                                  ),
                                )))
                            .values
                            .toList(),
                      ))
                ],
              ),
            ),
          ),
          SafeArea(
            bottom: true,
            child: Container(
              height: 45.h,
              decoration:
                  BoxDecoration(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
              alignment: Alignment.center,
              child: TextButton(
                  onPressed: () {
                    Get.back();
                    Future<void>.delayed(const Duration(milliseconds: 50), () {
                      Get.toNamed(RoutePath.bargainAccelerate);
                    });
                  },
                  child: Text(
                    '确定',
                    style: StylesUtils.customTextStyle(),
                  )),
            ),
          )
        ],
      ),
    ));
  }
}
